// 作业控制器
const { Homework, Class, User, Submission } = require('../models');
const { Op, Sequelize } = require('sequelize');

/**
 * 作业控制器
 * 处理作业相关的业务逻辑
 */
class HomeworkController {
  /**
   * 发布作业
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async createHomework(req, res) {
    try {
      const { title, content, classId, deadline } = req.body;
      const teacherId = req.user.id;

      // 验证输入
      if (!title || !content) {
        return res.status(400).json({
          success: false,
          message: '请输入作业名称和内容'
        });
      }

      // 处理附件路径
      let attachment = null;
      if (req.file) {
        attachment = `/uploads/${req.query.type || 'homework'}/${req.file.filename}`;
      }

      // 处理粘贴的图片数据
      let images = null;
      if (req.body.images) {
        try {
          // 解析前端发送的图片数据
          images = req.body.images;
        } catch (error) {
          console.error('解析图片数据失败:', error);
        }
      }

      // 创建作业
      const homework = await Homework.create({
        title,
        content,
        attachment,
        images,
        teacherId,
        classId,
        deadline: deadline ? new Date(deadline) : null
      });

      res.json({
        success: true,
        message: '作业发布成功',
        data: homework
      });
    } catch (error) {
      console.error('发布作业失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取作业列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getHomeworkList(req, res) {
    try {
      const { classId, grade } = req.query;
      const user = req.user;

      let whereCondition = {};

      // 如果是学生，只能查看自己班级的作业或面向全年级的作业
      if (user.role === 'student') {
        whereCondition = {
          [Op.or]: [
            { classId: user.classId },
            { classId: null }
          ]
        };
      }
      // 如果是教师，可以筛选班级
      else if (user.role === 'teacher') {
        if (classId) {
          whereCondition.classId = classId;
        }
        if (grade) {
          // 通过班级表关联查询年级
          whereCondition.include = [{ model: Class, as: 'classInfo', where: { grade } }];
        }
      }

      const homeworks = await Homework.findAll({
        where: whereCondition,
        include: [
          { model: User, as: 'teacher', attributes: ['id', 'username'] },
          { model: Class, as: 'classInfo', attributes: ['id', 'className', 'grade'] }
        ],
        order: [['createdAt', 'DESC']]
      });

      res.json({
        success: true,
        data: homeworks
      });
    } catch (error) {
      console.error('获取作业列表失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 获取作业详情
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getHomeworkById(req, res) {
    try {
      const { homeworkId } = req.params;

      const homework = await Homework.findByPk(homeworkId, {
        include: [
          { model: User, as: 'teacher', attributes: ['id', 'username'] },
          { model: Class, as: 'classInfo', attributes: ['id', 'className', 'grade'] }
        ]
      });

      if (!homework) {
        return res.status(404).json({
          success: false,
          message: '作业不存在'
        });
      }

      res.json({
        success: true,
        data: homework
      });
    } catch (error) {
      console.error('获取作业详情失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 更新作业
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async updateHomework(req, res) {
    try {
      const { homeworkId } = req.params;
      const { title, content, classId, deadline } = req.body;
      const teacherId = req.user.id;

      // 查找作业
      const homework = await Homework.findByPk(homeworkId);
      if (!homework) {
        return res.status(404).json({
          success: false,
          message: '作业不存在'
        });
      }

      // 检查权限（只有发布者可以修改）
      if (homework.teacherId !== teacherId) {
        return res.status(403).json({
          success: false,
          message: '没有权限修改此作业'
        });
      }

      // 处理附件路径
      let attachment = homework.attachment;
      if (req.file) {
        attachment = `/uploads/${req.query.type || 'homework'}/${req.file.filename}`;
      }

      // 处理粘贴的图片数据
      let images = homework.images;
      if (req.body.images !== undefined) {
        try {
          // 解析前端发送的图片数据
          images = req.body.images;
        } catch (error) {
          console.error('解析图片数据失败:', error);
        }
      }

      // 更新作业
      await homework.update({
        title: title || homework.title,
        content: content || homework.content,
        attachment,
        images,
        classId: classId !== undefined ? classId : homework.classId,
        deadline: deadline ? new Date(deadline) : homework.deadline
      });

      res.json({
        success: true,
        message: '作业更新成功',
        data: homework
      });
    } catch (error) {
      console.error('更新作业失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }

  /**
   * 删除作业
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async deleteHomework(req, res) {
    try {
      const { homeworkId } = req.params;
      const teacherId = req.user.id;

      // 查找作业
      const homework = await Homework.findByPk(homeworkId);
      if (!homework) {
        return res.status(404).json({
          success: false,
          message: '作业不存在'
        });
      }

      // 检查权限（只有发布者可以删除）
      if (homework.teacherId !== teacherId) {
        return res.status(403).json({
          success: false,
          message: '没有权限删除此作业'
        });
      }

      // 删除作业
      await homework.destroy();

      res.json({
        success: true,
        message: '作业删除成功'
      });
    } catch (error) {
      console.error('删除作业失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }
  
  /**
   * 获取学生可提交的作业列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getAvailableHomeworks(req, res) {
    try {
      const studentId = req.user.id;
      const studentClassId = req.user.classId;
      
      // 先查询学生所在班级和面向全年级的所有作业
      const allHomeworks = await Homework.findAll({
        where: {
          [Op.or]: [
            { classId: studentClassId },
            { classId: null }
          ]
        },
        include: [
          { model: User, as: 'teacher', attributes: ['id', 'username'] }
        ],
        attributes: ['id', 'title', 'content', 'attachment', 'createdAt', 'deadline'],
        order: [['createdAt', 'DESC']]
      });
      
      // 查询该学生所有的作业提交记录
      const studentSubmissions = await Submission.findAll({
        where: { studentId },
        attributes: ['homeworkId', 'isRejectedRecord']
      });
      
      // 创建一个映射，记录每个作业的最新提交状态
      const submissionMap = {};
      studentSubmissions.forEach(sub => {
        if (!submissionMap[sub.homeworkId] || sub.isRejectedRecord) {
          submissionMap[sub.homeworkId] = sub.isRejectedRecord;
        }
      });
      
      // 过滤出可提交的作业：未提交或已被退回的作业
      const availableHomeworks = allHomeworks.filter(homework => {
        // 如果作业没有提交记录，或者提交记录是被退回的，则可提交
        return !submissionMap.hasOwnProperty(homework.id) || submissionMap[homework.id];
      });
      
      res.json({
        success: true,
        data: availableHomeworks
      });
    } catch (error) {
      console.error('获取可提交作业列表失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }
}

module.exports = HomeworkController;